package com.lixiaoyao.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lixiaoyao.reggie.common.SMSUtils;
import com.lixiaoyao.reggie.common.ValidateCodeUtils;
import com.lixiaoyao.reggie.entity.R;
import com.lixiaoyao.reggie.entity.User;
import com.lixiaoyao.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String> getCode(@RequestBody User user, HttpServletRequest request){
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            SMSUtils.sendMessage(phone, String.valueOf(code));

            log.info(code.toString());
            //将验证码存到session中
            //request.getSession().setAttribute(phone,code);
            //将验证码存到session缓存中，并设置5分钟有效期
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");
    }
    @PostMapping("/login")
    public R<User> login (@RequestBody Map map, HttpServletRequest request){
        //1.判断用户是否登录
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        HttpSession session = request.getSession();

        //从session中获取验证码
        //String codeInfo = session.getAttribute(phone).toString();
        //从redis缓存中获取验证码
        String codeInfo = redisTemplate.opsForValue().get(phone).toString();
        if(!code.equals(codeInfo)){
            return R.error("验证码错误");
        }
        //2.将user存到session中，并判断用户是否注册，未注册则自动注册
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(queryWrapper);
        if(user==null){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        request.getSession().setAttribute("user",user.getId());

        //用户登录成功后删除验证码
        redisTemplate.delete(phone);

        return R.success(user);
    }
}
